package com.emm.yixun.mobile.ui.customer;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.clam314.lame.Mp3Recorder;
import com.demo.utils.PathUtils;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.adapter.FollowUpAdapter;
import com.emm.yixun.mobile.adapter.MainProjectAdapter;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.AddCustomer;
import com.emm.yixun.mobile.model.AddFollow;
import com.emm.yixun.mobile.model.GetCustomerDetail;
import com.emm.yixun.mobile.model.GetFollowList;
import com.emm.yixun.mobile.model.GetFollowList.FollowList;
import com.emm.yixun.mobile.model.GetFollowList.FollowList.ContentList;
import com.emm.yixun.mobile.model.GetProjectList;
import com.emm.yixun.mobile.model.GetProjectList.ProjectList;
import com.eroad.product.tools.MyListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nui.multiphotopicker.view.ImageBucketChooseActivity;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yanzhenjie.album.Album;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.functions.Consumer;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import xf.tools.Loading;

import static android.Manifest.permission.RECORD_AUDIO;

/**
 * <p>
 * <b>Title：</b>跟进界面
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 *
 * @author tangxin
 * @date 2016年12月6日 下午4:07:49
 */
public class FollowUpActivity extends SwipeBackActivity {

    private static final String TAG = "FollowUpActivity";

    /**
     * 客户ID
     */
    private String customerId;

    /**
     * 性别
     */
    private String SEX;

    /**
     * 评分
     */
    private String NUMBER;

    /**
     * 客户状态
     */
    private String CUSTOMER_STATUS;

    /**
     * 客户来源
     */
    private String CUSTOMER_ORIGIN;

    /**
     * 标星
     */
    private String STAR;

    /**
     * 姓名
     */
    private String NAME;

    /**
     * 电话
     */
    private String TEL;

    /**
     * 拍照图片路径
     */
    private Uri mImageCaptureUri;

    /**
     * 拍照
     */
    private static final int PICK_FROM_CAMERA = 1;

    /**
     * 裁剪
     */
    private static final int CROP_FROM_CAMERA = 2;

    /**
     * 相册
     */
    private static final int PICK_FROM_FILE = 3;

    /**
     * 次级菜单开关 false关 true开
     */
    private boolean Isopen = false;

    /**
     * 三级菜单开关 false关 true开
     */
    private boolean Isvideo = false;

    /**
     * 标题
     */
    TextView title_main;

    /**
     * back按扭
     */
    ImageView back_btn;

    /**
     * 菜单按钮
     */
    ImageView more_btn;

    /**
     * 录音按钮
     */
    ImageView start_buttom;

    /**
     * 拍照
     */
    ImageView picture;

    /**
     * 三级菜单
     */
    LinearLayout linear3;

    /**
     * 三级菜单开关
     */
    ImageView open_video;

    /** 次级菜单 */
    // LinearLayout linear2;

    /** 次级菜单开关 */
    // ImageView open_image;

    /**
     * 输入框
     */
    EditText content_ed;

    /**
     * 发送按钮
     */
    TextView send;

    View view;

    /**
     * 打开相册
     */
    ImageView open_pir;

    /**
     * 跟进记录适配器
     */
    FollowUpAdapter adapter;

    /**
     * 跟进记录列表
     */
    MyListView genjin_list;

    GetFollowList followmodel;

    /**
     * 最近对应名
     */
    // private File audioFile;
    private Context context;

    /**
     * 音频路径
     */
    private String patchMp3;

    private int frequence = 16000;// 8000;
    private int channelConfig = AudioFormat.CHANNEL_CONFIGURATION_MONO;
    private int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;

    MediaPlayer mp;
    int openaac = 0;

    /**
     * 播放录音布局
     */
    RelativeLayout play_video;

    /**
     * 关闭按钮
     */
    ImageView close_btn;

    /**
     * 播放提示view
     */
    TextView tson_textcontent;

    /**
     * 播放效果
     */
    ImageView image_icon;

    /**
     * 名称
     */
    TextView user_name;

    LinearLayout CallPhone;

    private String defPatch;

    TextView phone_tel;

    /**
     * 跟进ID
     */
    private String FollowId;

    /**
     * 未拨通
     */
    LinearLayout callDnt;

    /**
     * 快速跟进，未接通
     */
    TextView cancel_call;

    /**
     * 星标
     */
    TextView user_star;
    /**
     * 性别
     */
    TextView user_sex;
    /**
     * 号码
     */
    TextView user_number;
    /**
     * 状态
     */
    TextView customerStatus;
    /**
     * 来源
     */
    TextView customerOrigin;

    /**
     * 录音旋转图片
     */
    ImageView move_image;

    /**
     * 录音动画效果布局
     */
    RelativeLayout set_video;

    /**
     * 旋转动画
     */
    Animation operatingAnim;

    /**
     * 倒计时时间
     */
    TextView count_down;
    /**
     * 时间累积值
     */
    private int hourTimes = 0;
    /**
     * 交互触发累积值
     */
    private int countTimes = 0;
    /**
     * 点触状态
     */
    private boolean IsOpenTimer = false;
    /**
     * 动画模拟指标
     */
    int count;

    /**
     * 侧滑关闭框架
     */
    private SwipeBackLayout mSwipeBackLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        IsVisibleStatusBar = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.follow_up_activity);

        SetSwipeBackLayout(mSwipeBackLayout);

        BaseActivity.activity = this;
        defPatch = PathUtils.Companion.getVideoFile(FollowUpActivity.this).getPath();
        customerId = getIntent().getStringExtra("customerId");

        Log.v(TAG, "customerId:" + customerId + "/SEX:" + SEX + "/NUMBER" + NUMBER + "/CUSTOMER_STATUS:"
                + CUSTOMER_STATUS + "/CUSTOMER_ORIGIN:" + CUSTOMER_ORIGIN + "/STAR:" + STAR + "/FollowId:" + FollowId);

        initView();

        findViewById(R.id.statusbar_bg).setVisibility(View.GONE);

        initBtn();
        openForType = 2;
        requestPermissions();
    }

    private void requestPermissions() {
        RxPermissions rxPermission = new RxPermissions(this);
        rxPermission.requestEach(RECORD_AUDIO)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            getFollowList(customerId);
                            InitMP3();
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            finish();
                        } else {
                            finish();
                        }
                    }
                });
    }

    /**
     * <p>
     * <b>Title：</b> 初始化view
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午2:37:21
     */
    private void initView() {
        view = findViewById(R.id.follow_up);
        title_main = (TextView) findViewById(R.id.title_main);
        title_main.setText(getString(R.string.follow_cosutmoer));
        back_btn = (ImageView) findViewById(R.id.back_btn);
        more_btn = (ImageView) findViewById(R.id.more_btn);
        start_buttom = (ImageView) findViewById(R.id.start_buttom);
        picture = (ImageView) findViewById(R.id.picture);
        linear3 = (LinearLayout) findViewById(R.id.linear3);
        open_video = (ImageView) findViewById(R.id.open_video);
        content_ed = (EditText) findViewById(R.id.content_ed);
        send = (TextView) findViewById(R.id.send);
        open_pir = (ImageView) findViewById(R.id.open_pir);
        genjin_list = (MyListView) findViewById(R.id.genjin_list);
        play_video = (RelativeLayout) findViewById(R.id.play_video);
        close_btn = (ImageView) findViewById(R.id.close_btn);
        tson_textcontent = (TextView) findViewById(R.id.tson_textcontent);
        image_icon = (ImageView) findViewById(R.id.image_icon);
        user_name = (TextView) findViewById(R.id.user_name);
        user_name.setText(NAME);
        CallPhone = (LinearLayout) findViewById(R.id.CallPhone);
        user_star = (TextView) findViewById(R.id.user_star);
        callDnt = (LinearLayout) findViewById(R.id.calldnt);
        cancel_call = (TextView) findViewById(R.id.cancel_call);

        if (EmmApplication.isNull(FollowId)) {
            SelectPotion = 3;
            callDnt.setVisibility(View.VISIBLE);
        } else {// 并非拨号
            callDnt.setVisibility(View.GONE);
        }

        if ("1".equals(STAR) || "是".equals(STAR)) {
            user_star.setVisibility(View.VISIBLE);
        } else {
            user_star.setVisibility(View.INVISIBLE);
        }
        user_sex = (TextView) findViewById(R.id.user_sex);
        user_sex.setText(SEX);
        if ("1".equals(SEX)) {
            user_sex.setText("男");
        }
        if ("0".equals(SEX)) {
            user_sex.setText("女");
        }
        user_number = (TextView) findViewById(R.id.user_number);
        user_number.setText(NUMBER);
        phone_tel = (TextView) findViewById(R.id.phone_tel);
        phone_tel.setText(TEL);
        customerStatus = (TextView) findViewById(R.id.customerstatus);
        customerStatus.setText(CUSTOMER_STATUS);
        customerOrigin = (TextView) findViewById(R.id.customeorigin);
        customerOrigin.setText(CUSTOMER_ORIGIN);
        move_image = (ImageView) findViewById(R.id.move_image);
        set_video = (RelativeLayout) findViewById(R.id.set_video);
        count_down = (TextView) findViewById(R.id.count_down);

        operatingAnim = AnimationUtils.loadAnimation(this, R.anim.tip);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);

    }

    /**
     * <p>
     * <b>Title：</b> 初始化监听事件
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午2:39:17
     */
    private void initBtn() {
        back_btn.setVisibility(View.VISIBLE);
        back_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPlayer) {
                    isPlayer = false;
                    if (mp != null) {
                        mp.stop();
                    }
                } else {
                    finish();
                }
            }
        });

        more_btn.setVisibility(View.VISIBLE);
        more_btn.setImageResource(R.drawable.icon_jia);
        more_btn.setOnClickListener(new OnClickListener() {// 加号
            @Override
            public void onClick(View v) {
                setSortPoPu();
            }
        });

        // 注册touch事件，做长按事件处理
        start_buttom.setOnTouchListener(onTouch);

        picture.setOnClickListener(new OnClickListener() {// 拍照
            @Override
            public void onClick(View v) {
                Isvideo = false;
                linear3.setVisibility(View.GONE);
                Album.camera(activity).start(PICK_FROM_CAMERA);
            }
        });

        open_pir.setOnClickListener(new OnClickListener() {// 打开相册
            @Override
            public void onClick(View v) {
                Isvideo = false;
                linear3.setVisibility(View.GONE);
                // 打开相册选择
                EmmApplication.IsMoreSelect = true;
                EmmApplication.pir.clear();// 不支持多次复合性选择，每次选择都要清空前面的数据
                EmmApplication.setData("Picture", "1");
                startActivity(new Intent(FollowUpActivity.this, ImageBucketChooseActivity.class));
            }
        });

        content_ed.setOnClickListener(new OnClickListener() {// 输入框
            @Override
            public void onClick(View v) {
                // linear2.setVisibility(View.GONE);
                linear3.setVisibility(View.GONE);
            }
        });

        content_ed.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            // 当键盘弹出隐藏的时候会 调用此方法。
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                // 获取当前界面可视部分
                FollowUpActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                // 获取屏幕的高度
                int screenHeight = FollowUpActivity.this.getWindow().getDecorView().getRootView().getHeight();
                // 此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                int heightDifference = screenHeight - r.bottom;
                Log.v(TAG, "Size: " + heightDifference);
            }
        });

        send.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 调用提交接口，并刷新界面
                if (EmmApplication.isNull(content_ed.getText().toString().trim())) {
                    EmmApplication.disKey(FollowUpActivity.this);
                    SendDetails(content_ed.getText().toString().trim());
                    content_ed.setText("");
                }
            }
        });

        open_video.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 打开三级菜单
                if (Isvideo) {
                    Isvideo = false;
                    linear3.setVisibility(View.GONE);
                } else {
                    Isvideo = true;
                    linear3.setVisibility(View.VISIBLE);
                }
            }
        });

        close_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (openaac == 0) {
                    if (mp != null) {
                        mp.pause();
                        EmmApplication.setVideo(EmmApplication.current);
                    }
                } else {
                }
                play_video.setVisibility(View.GONE);
                handler.removeMessages(99);
                EmmApplication.setLog(FollowUpActivity.this);
            }
        });
        play_video.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.v(TAG, "play_video-->");
            }
        });

        cancel_call.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                editFollow();
            }
        });
    }

    /**
     * 点击监听事件
     */
    public OnTouchListener onTouch = new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:// 点击
                    Log.w(TAG, "ACTION_DOWN");

                    set_video.setVisibility(View.VISIBLE);

                    if (operatingAnim != null) {
                        move_image.startAnimation(operatingAnim);
                    }

                    EmmApplication.showTips("请对准话筒录音");// 短语音时间上限60秒

                    // 开始录音
                    IsOpenTimer = true;

                    Mp3Name = System.currentTimeMillis() + ".mp3";
                    patchMp3 = defPatch + "/" + Mp3Name;
                    try {
                        recorder_Mp3.startRecording(new File(patchMp3));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    Log.w(TAG, "patchMp3:" + patchMp3);

                    Message message = handler.obtainMessage(1);
                    handler.sendMessageDelayed(message, 1000);
                    Message message2 = handler.obtainMessage(2);
                    handler.sendMessageDelayed(message2, 1);

                    break;
                case MotionEvent.ACTION_UP:// 抬起
                    Log.w(TAG, "ACTION_UP===>countTimes:" + countTimes + "---->hourTimes:" + hourTimes);
                    // 停止录音
                    set_video.setVisibility(View.GONE);
                    if (operatingAnim != null) {
                        move_image.clearAnimation();
                    }

                    try {
                        recorder_Mp3.stopRecording();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    int countnumber = (int) (hourTimes / 10);
                    IsOpenTimer = false;
                    // 需要判断时长是否超过一秒
                    if (countnumber < 1) {
                        EmmApplication.showTips("录音时间过短");
                        // 执行删除
                        EmmApplication.deleteFile(new File(patchMp3));
                    } else {// 执行发送录音文件
                        hourTimes = 0;
                        SetVideo(patchMp3, SetTimer(countnumber), "" + countnumber);
                    }
                    break;
            }
            return true;
        }
    };

    /**
     * 伪异步处理，刷新界面展示效果
     */
    @SuppressLint("HandlerLeak")
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (IsOpenTimer) {
                        double number = (600 - hourTimes);
                        count_down.setText((number / 10) + " s");
                        if (number <= 0) {// 已达时间上限，提示停止录音
                            count_down.setText("0");
                            try {
                                recorder_Mp3.stopRecording();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            EmmApplication.showTips("已达时间上限，请松开提交录音");
                        } else {
                            hourTimes++;
                            Message message = handler.obtainMessage(1);
                            handler.sendMessageDelayed(message, 100);
                        }
                    } else {
                        hourTimes = 0;
                    }
                    break;
                case 2:
                    if (IsOpenTimer) {
                        countTimes++;
                        Message message2 = handler.obtainMessage(2);
                        handler.sendMessageDelayed(message2, 1);
                    } else {
                        countTimes = 0;
                    }
                    break;
                case 3:
                    EmmApplication.T2("图片错误，请重新选择");
                    getFollowList(customerId);
                    break;
                case 99:
                    if (count == 0) {
                        handler.removeMessages(99);
                    } else {
                        if (count % 4 == 0) {// 模拟帧动画效果
                            image_icon.setImageResource(R.drawable.a01v);
                        } else if (count % 4 == 1) {
                            image_icon.setImageResource(R.drawable.a02v);
                        } else if (count % 4 == 2) {
                            image_icon.setImageResource(R.drawable.a03v);
                        } else if (count % 4 == 3) {
                            image_icon.setImageResource(R.drawable.a04v);
                        }
                        count++;
                        Message message = handler.obtainMessage(99);
                        handler.sendMessageDelayed(message, 500);
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    /**
     * <p>
     * <b>Title：</b> 时间格式化
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param c 秒
     * @return
     * @author tangxin
     * @date 2016年12月7日 下午2:41:53
     */
    private String SetTimer(int c) {
        String timedate = "";
        int y = 0;// 年
        int mt = 0;// 月
        int d = 0;// 日
        int h = 0;// 小时
        int m = 0;// 分
        int s = 0;// 秒
        s = c % 60;// 最小单位为秒，以分为摄取对象，模之后的值为秒
        m = (c - s) / 60; // 获取总的分钟数
        if (m >= 60) {
            h = (int) (m / 60);// 获取小时,值获取整数部分，免去取模值部分步骤
            m = m - h * 60;// 总分钟数减去转化为小时部分，剩余值为分钟
        } else {
            h = 0;// 不足一小时
        }
        if (h > 0) {
            timedate = h + "°";
        }
        if (m > 0) {// 大于0，需判断是一位数还是多位数
            if (m >= 10) {
                timedate += "" + m + "′";
            } else {
                timedate += "0" + m + "′";
            }
        } else {
            timedate += "00′";
        }
        if (s > 0) {
            if (s >= 10) {
                timedate += "" + s + "″";
            } else {
                timedate += "0" + s + "″";
            }
        } else {
            timedate += "00" + "″";
        }
        return timedate;
    }

    /**
     * 回调方法
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.w("a", +requestCode + "resultCode===" + resultCode + "RESULT_OK======" + RESULT_OK);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case PICK_FROM_CAMERA:
                SetPictrueImage(Album.parseResult(data).get(0));
                break;
            case PICK_FROM_FILE:
                Log.w("a", "相册");
                mImageCaptureUri = data.getData();
                break;
            case CROP_FROM_CAMERA:
                Log.w("CROP_FROM_CAMERA", "CROP_FROM_CAMERA");
                break;
            case 0:
                System.out.println("相册");
                break;
            default:
                break;
        }
    }

    /**
     * 按键监听事件
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isPlayer) {// 在播放过程中按返回，先停止播放
                if (mp != null) {
                    mp.stop();
                    EmmApplication.setVideo(EmmApplication.current);
                }
            } else {
                finish();
            }
        } else {
        }
        return super.onKeyDown(keyCode, event);
    }

    View viewProject;
    PopupWindow PoPuProject;

    /**
     * 选中的类型
     */
    private int SelectPotion = 0;

    /**
     * <p>
     * <b>Title：</b> 类型切换
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午2:42:40
     */
    public void setSortPoPu() {
        viewProject = LayoutInflater.from(FollowUpActivity.this).inflate(R.layout.mainproject_popu, null);
        PoPuProject = new PopupWindow(viewProject, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
                android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
        PoPuProject.setFocusable(true);
        PoPuProject.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        PoPuProject.showAtLocation(view, Gravity.TOP, 0, 0);
        PoPuProject.setFocusable(true);
        PoPuProject.setOutsideTouchable(true);
        viewProject.setFocusable(true);
        viewProject.setFocusableInTouchMode(true);
        viewProject.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    PoPuProject.dismiss();
                    EmmApplication.setLog(FollowUpActivity.this);
                }
                return false;
            }
        });
        viewProject.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                PoPuProject.dismiss();
                EmmApplication.setLog(FollowUpActivity.this);
            }
        });
        ListView popu_list = (ListView) viewProject.findViewById(R.id.popu_list);

        RelativeLayout top_relativelayout = (RelativeLayout) viewProject.findViewById(R.id.top_relativelayout);
        SetViewPaddingHeight(top_relativelayout, 51);

        final GetProjectList list = new GetProjectList();
        ArrayList<ProjectList> ll = new ArrayList<ProjectList>();
        ProjectList m = new ProjectList();
        m.setProjectCode("1");
        m.setProjectName("来电");
        ll.add(m);
        ProjectList m1 = new ProjectList();
        m1.setProjectCode("2");
        m1.setProjectName("来访");
        ll.add(m1);
        ProjectList m2 = new ProjectList();
        m2.setProjectCode("3");
        m2.setProjectName("信息");
        ll.add(m2);
        ProjectList m3 = new ProjectList();
        m3.setProjectCode("4");
        m3.setProjectName("去电");
        ll.add(m3);
        ProjectList m4 = new ProjectList();
        m4.setProjectCode("5");
        m4.setProjectName("拜访");
        ll.add(m4);
        ProjectList m5 = new ProjectList();
        m5.setProjectCode("7");
        m5.setProjectName("微信");
        ll.add(m5);
        list.setProjectList(ll);
        MainProjectAdapter adapter = new MainProjectAdapter(FollowUpActivity.this, list);
        popu_list.setAdapter(adapter);
        adapter.SeleCt(SelectPotion);
        adapter.SetType(1);
        popu_list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SelectPotion = position;
                PoPuProject.dismiss();
                EmmApplication.setLog(FollowUpActivity.this);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        BaseActivity.activity = this;
        IntentFilter filter = new IntentFilter(EmmApplication.SendBroadcastContent);
        registerReceiver(mBroadcastReceiver, filter);
        IntentFilter filter2 = new IntentFilter(EmmApplication.SendOpenVideo);
        registerReceiver(mBroadcastReceiver, filter2);
    }

    /**
     * 是否处于播放状态
     */
    private boolean isPlayer = false;

    /**
     * 广播，处理播放录音，发送图片操作
     */
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(EmmApplication.SendBroadcastContent)) {
                /* 触发图片发送动作 */
                SetImage();
            } else if (action.equals(EmmApplication.SendOpenVideo)) {
                // 播录音
                File audioFile = EmmApplication.OpenPath;// 得到路径，重置值给播放提供条件
                Log.v(TAG, "audioFile.toString()" + audioFile.toString());
                if ("aac".equals(audioFile.toString().substring(audioFile.toString().length() - 3,
                        audioFile.toString().length()))
                        || "mp3".equals(audioFile.toString().substring(audioFile.toString().length() - 3,
                        audioFile.toString().length()))
                        || "wav".equals(audioFile.toString().substring(audioFile.toString().length() - 3,
                        audioFile.toString().length()))
                        || "WAV".equals(audioFile.toString().substring(audioFile.toString().length() - 3,
                        audioFile.toString().length()))) {
                    isPlayer = true;
                    openaac = 0;
                    EmmApplication.getVideo();
                    EmmApplication.setVideo(EmmApplication.max);
                    count = 1;
                    handler.sendEmptyMessage(99);
                    play_video.setVisibility(View.VISIBLE);
                    mp = new MediaPlayer();
                    try {
                        mp.setDataSource(audioFile.toString());
                        mp.prepare();
                        mp.start();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mp.setOnCompletionListener(new OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            Log.v(TAG, "播放完成:->");
                            mp.release();
                            isPlayer = false;
                            EmmApplication.setVideo(EmmApplication.current);
                            play_video.setVisibility(View.GONE);
                            handler.removeMessages(99);
                        }
                    });
                } else {
                    openaac = 1;
                    if (isPlayer) {
                        EmmApplication.showTips("正在播放");
                    } else {
                        EmmApplication.getVideo();
                        EmmApplication.setVideo(EmmApplication.max);
                        count = 1;
                        handler.sendEmptyMessage(99);
                        play_video.setVisibility(View.VISIBLE);
                        PlayTask player = new PlayTask();
                        player.execute();
                    }
                }
            }
        }
    };

    protected void onDestroy() {
        super.onDestroy();

        EmmApplication.IS_RELOAD_DETAILS = true;

        Log.v(TAG, "onDestroy");
        EmmApplication.pir.clear();
        unregisterReceiver(mBroadcastReceiver);

        if (null != recorder_Mp3) {// 录制过程中关闭界面就停止录制
            try {
                recorder_Mp3.stopRecording();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 侧滑关闭界面时，关闭正在播放的录音和发送广播去刷新客户详情界面
        if (isPlayer) {
            isPlayer = false;
            if (mp != null) {
                mp.stop();
            }
            EmmApplication.setVideo(EmmApplication.current);
        }

        if (null != mp) {// 播放过程中关闭界面就停止播放
            mp.release();
        }

        sendBroadcast(new Intent(EmmApplication.NEW_CUSTOMER_DETAILS));
    }

    ;

    /**
     * <p>
     * <b>Title：</b> 以下标为key拿到value
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param s
     * @return
     * @author tangxin
     * @date 2016年12月7日 下午2:43:11
     */
    private String typename(int s) {
        if (s == 0) {
            return "来电";
        } else if (s == 1) {
            return "来访";
        } else if (s == 2) {
            return "信息";
        } else if (s == 3) {
            return "去电";
        } else if (s == 4) {
            return "拜访";
        } else if (s == 5) {
            return "微信";
        } else {
            return "来电";
        }
    }

    /**
     * <p>
     * <b>Title：</b> 发送文本信息
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param str
     * @author tangxin
     * @date 2016年12月7日 下午2:43:18
     */
    private void SendDetails(String str) {
        ArrayList<FollowList> followList = new ArrayList<GetFollowList.FollowList>();
        FollowList f = new FollowList();

        f.setFollowMode(typename(SelectPotion));
        f.setFollowTime(EmmApplication.dataTime(EmmApplication.geTime(), "yyyy-MM-dd"));
        f.setFollowType("1");
        ArrayList<ContentList> contentList = new ArrayList<GetFollowList.FollowList.ContentList>();
        ContentList c = new ContentList();
        c.setFollowContent(str);
        contentList.add(c);
        f.setContentList(contentList);
        followList.add(0, f);
        adapter.SetDeta(followList);

        ArrayList<ContentListinfo> contentList_ = new ArrayList<ContentListinfo>();
        ContentListinfo content = new ContentListinfo();
        content.setFollowContent(str);
        contentList_.add(content);
        addfollow(contentList_, customerId, SelectPotion, "1", "", "", "", "");
    }

    /**
     * <p>
     * <b>Title：</b> 发送图片
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午2:43:29
     */
    private void SetImage() {
        ArrayList<FollowList> followList = new ArrayList<GetFollowList.FollowList>();
        FollowList f = new FollowList();
        f.setFollowMode(typename(SelectPotion));
        f.setFollowTime(EmmApplication.dataTime(EmmApplication.geTime(), "yyyy-MM-dd"));
        f.setFollowType("2");
        ArrayList<ContentList> contentList = new ArrayList<GetFollowList.FollowList.ContentList>();
        for (int i = 0; i < EmmApplication.pir.size(); i++) {
            ContentList c = new ContentList();
            c.setFollowContent("file://" + EmmApplication.pir.get(i).sourcePath);
            contentList.add(c);
        }
        f.setContentList(contentList);
        followList.add(0, f);
        if (adapter != null) {
            adapter.SetDeta(followList);
        } else {
            getFollow.getFollowList().addAll(followList);
            adapter = new FollowUpAdapter(FollowUpActivity.this, getFollow, 2);
            genjin_list.setAdapter(adapter);
        }

        Loading.hideDialogForLoading();
        Loading.showDialogForLoading(FollowUpActivity.this, "正在转码上传...", false, true, 150000);
        RecordTaskUpdate po = new RecordTaskUpdate(3, null, null);
        po.execute();
    }

    /**
     * <p>
     * <b>Title：</b> 拍照图片发送
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param path
     * @author tangxin
     * @date 2016年12月7日 下午2:43:40
     */
    private void SetPictrueImage(String path) {
        ArrayList<FollowList> followList = new ArrayList<GetFollowList.FollowList>();
        FollowList f = new FollowList();
        f.setFollowMode(typename(SelectPotion));
        f.setFollowTime(EmmApplication.dataTime(EmmApplication.geTime(), "yyyy-MM-dd"));
        f.setFollowType("2");
        ArrayList<ContentList> contentList = new ArrayList<GetFollowList.FollowList.ContentList>();
        ContentList c = new ContentList();
        c.setFollowContent("file://" + path);
        contentList.add(c);
        f.setContentList(contentList);
        followList.add(0, f);
        if (adapter != null) {
            adapter.SetDeta(followList);
        } else {
            getFollow.getFollowList().addAll(followList);
            adapter = new FollowUpAdapter(FollowUpActivity.this, getFollow, 2);
            genjin_list.setAdapter(adapter);
        }

        Loading.hideDialogForLoading();
        Loading.showDialogForLoading(FollowUpActivity.this, "正在转码上传...", false, true, 150000);
        RecordTaskUpdate po = new RecordTaskUpdate(1, path, null);
        po.execute();
    }

    /**
     * <p>
     * <b>Title：</b> 录音发送
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param path
     * @param times
     * @param count
     * @author tangxin
     * @date 2016年12月7日 下午2:43:58
     */
    private void SetVideo(String path, String times, String count) {
        ArrayList<FollowList> followList = new ArrayList<GetFollowList.FollowList>();
        FollowList f = new FollowList();
        f.setFollowMode(typename(SelectPotion));
        f.setFollowTime(EmmApplication.dataTime(EmmApplication.geTime(), "yyyy-MM-dd"));
        f.setFollowType("3");
        ArrayList<ContentList> contentList = new ArrayList<GetFollowList.FollowList.ContentList>();
        ContentList c = new ContentList();
        c.setFollowContent(path);
        contentList.add(c);
        f.setVoiceLocalAddr(path);
        f.setVoiceTime(times);
        f.setContentList(contentList);
        followList.add(0, f);
        if (adapter != null) {
            adapter.SetDeta(followList);
        } else {
            getFollow.getFollowList().addAll(followList);
            adapter = new FollowUpAdapter(FollowUpActivity.this, getFollow, 2);
            genjin_list.setAdapter(adapter);
        }
        Loading.hideDialogForLoading();
        Loading.showDialogForLoading(FollowUpActivity.this, "正在转码上传...", false, true, 150000);
        RecordTaskUpdate po = new RecordTaskUpdate(2, path, times);
        po.execute();
        // 关闭键盘
        EmmApplication.disKey(FollowUpActivity.this);
        // 打开(关闭)次级菜单
        if (Isopen) {// 次级菜单开关 false关 true开
            Isopen = false;
            // linear2.setVisibility(View.GONE);
            linear3.setVisibility(View.GONE);
        } else {
            Isopen = true;
            // linear2.setVisibility(View.VISIBLE);
            if (Isvideo) {// 三级菜单开关 false关 true开
                linear3.setVisibility(View.VISIBLE);
            } else {
                linear3.setVisibility(View.GONE);
            }
        }
    }

    public static class ContentListinfo {
        private String followContent;// 跟进内容

        public String getFollowContent() {
            return followContent;
        }

        public void setFollowContent(String followContent) {
            this.followContent = followContent;
        }
    }

    AddFollow addfollow;

    /**
     * <p>
     * <b>Title：</b> 新增跟进
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param contentList    跟进类容list
     * @param customerId     客户ID
     * @param followMode     跟进方式
     * @param followType     跟进内容类型
     * @param imageType      图片类型
     * @param voiceTime      录音时间
     * @param voiceLocalAddr 录音地址
     * @param format         文件格式
     * @author tangxin
     * @date 2016年12月7日 下午2:44:15
     */
    private void addfollow(ArrayList<ContentListinfo> contentList, final String customerId, int followMode,
                           String followType, String imageType, String voiceTime, String voiceLocalAddr, String format) {
        EmmApplication.updateUrl("addFollow");
        Map<String, Object> map = new HashMap<String, Object>();

        if (SelectPotion < 0) {
            EmmApplication.T("请点击右上角选择跟进类型");
            return;
        }
        if (EmmApplication.isNull(FollowId)) {
            Log.v(TAG, "FollowId:" + FollowId);
            map.put("followId", FollowId);
        }
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        map.put("projectCode", EmmApplication.getProjectCode());
        map.put("projectId", EmmApplication.getProjectID());
        map.put("customerId", customerId);
        map.put("followMode", "" + ((SelectPotion == 5 ? 6 : SelectPotion) + 1));// 微信类型为7
        map.put("followType", followType);
        map.put("imageType", imageType);
        map.put("voiceTime", voiceTime);
        map.put("voiceLocalAddr", voiceLocalAddr);
        map.put("format", format);
        map.put("contentList", contentList);
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v("addFollow-->post", EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                Loading.hideDialogForLoading();
                Log.v(TAG, "content:" + content);
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }

                addfollow = JSONObject.parseObject(resData.toString(), AddFollow.class);
                if ("1".equals(addfollow.getResult())) {
                    Log.v("获取成功", "");
                    openForType = 2;
                    if (EmmApplication.isNull(FollowId)) {
                        getFollowList(customerId);
                    }
                } else {
                    EmmApplication.T(addfollow.getErrorMsg().toString());
                    // 新增失败，刷新界面
                    getFollowList(customerId);
                    try {
                        Log.v("获取失败", "errorCode:" + addfollow.getErrorCode().toString() + "errorMsg:"
                                + addfollow.getErrorMsg().toString());
                    } catch (NullPointerException e) {
                        Log.v("客户详情，错误信息获取空指针异常", "");
                    }
                }
            }
        });
    }

    /**
     * <p>
     * <b>Title：</b> 根据patch转base64
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param path 需要转换的路径
     * @return
     * @throws Exception
     * @author tangxin
     * @date 2016年12月7日 下午2:44:29
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return Base64.encodeToString(buffer, Base64.DEFAULT);
    }

    /**
     * <p>
     * <b>Title：</b> 播放时，需要传入路径
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午2:44:39
     */
    class PlayTask extends AsyncTask<Void, Integer, Void> {
        @Override
        protected Void doInBackground(Void... arg0) {
            isPlayer = true;
            int bufferSize = AudioTrack.getMinBufferSize(frequence, channelConfig, audioEncoding);
            short[] buffer = new short[bufferSize / 4];
            try {
                Log.w("路径:", "" + patchMp3);
                // 定义输入流，将音频写入到AudioTrack类中，实现播放
                DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(
                        new File(patchMp3))));
                // 实例AudioTrack
                AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC, frequence, channelConfig, audioEncoding,
                        bufferSize, AudioTrack.MODE_STREAM);
                // 开始播放
                track.play();
                // 由于AudioTrack播放的是流，所以，我们需要一边播放一边读取
                while (isPlayer && dis.available() > 0) {
                    int i = 0;
                    while (dis.available() > 0 && i < buffer.length) {
                        buffer[i] = dis.readShort();
                        i++;
                    }
                    // 然后将数据写入到AudioTrack中
                    track.write(buffer, 0, buffer.length);
                }
                // 播放结束
                track.stop();
                dis.close();
                isPlayer = false;// 重置标识
                EmmApplication.setVideo(EmmApplication.current);
                play_video.setVisibility(View.GONE);
                handler.removeMessages(99);
                EmmApplication.setLog(FollowUpActivity.this);
            } catch (Exception e) {
            }
            return null;
        }

        protected void onPostExecute(Void result) {
        }

        protected void onPreExecute() {
        }
    }

    /**
     * 跟进列表
     */
    GetFollowList getFollow;

    private int openForType = 1;

    /**
     * <p>
     * <b>Title：</b> 跟进列表
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param customerId
     * @author tangxin
     * @date 2016年12月7日 下午3:01:51
     */
    private void getFollowList(final String customerId) {
        EmmApplication.updateUrl("getFollowList");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        map.put("projectCode", EmmApplication.getProjectCode());
        map.put("customerId", customerId);
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v("getFollowList-->post", EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                if (openForType != 1) {
                    openForType = 1;
                    Loading.showDialogForLoading(FollowUpActivity.this, "正在加载...", false, true, 60000);
                }
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                Log.v(TAG, "followup content:" + content);
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }

                getFollow = JSONObject.parseObject(resData.toString(), GetFollowList.class);
                if ("1".equals(getFollow.getResult())) {
                    Log.v("获取成功", "");
                    if (null != getFollow) {
                        adapter = new FollowUpAdapter(FollowUpActivity.this, getFollow, 2);
                        genjin_list.setAdapter(adapter);
                    }
                    getCustomerDetail(customerId);
                } else {
                    EmmApplication.T(getFollow.getErrorMsg().toString());
                    try {
                        Log.v("获取失败", "errorCode:" + getFollow.getErrorCode().toString() + "errorMsg:"
                                + getFollow.getErrorMsg().toString());
                    } catch (NullPointerException e) {
                        Log.v("客户详情，错误信息获取空指针异常", "");
                    }
                }
            }
        });
    }

    /**
     * <p>
     * <b>Title：</b> 新增跟进
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午3:04:21
     */
    class RecordTaskUpdate extends AsyncTask<Void, Integer, Void> {
        int type = 0;
        String path;
        String times;

        public RecordTaskUpdate(int type, String path, String times) {
            this.type = type;
            this.path = path;
            this.times = times;
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            if (type == 1) {// 图片
                Log.v(TAG, "拍照上传图片");
                ArrayList<ContentListinfo> contentList_ = new ArrayList<ContentListinfo>();
                ContentListinfo content = new ContentListinfo();
                Log.v(TAG, "拍照图片转base64");
                try {
                    content.setFollowContent(EmmApplication.setPatchRtString(path));
                    Log.v(TAG, "拍照图片转base64完成");
                    contentList_.add(content);
                    Log.v(TAG, "拍照图片调起上传");
                    addfollow(contentList_, customerId, SelectPotion, "2", ".jpg", "", "", "");
                } catch (Exception e) {
                    Loading.hideDialogForLoading();
                    handler.sendEmptyMessage(3);
                }
            } else if (type == 2) {// 录音
                Log.v(TAG, "录音");
                ArrayList<ContentListinfo> contentList_ = new ArrayList<ContentListinfo>();
                try {
                    ContentListinfo content = new ContentListinfo();
                    content.setFollowContent(encodeBase64File(path));
                    Log.v(TAG, "Base64 for String  length:" + content.getFollowContent().toString().length());
                    contentList_.add(content);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                addfollow(contentList_, customerId, SelectPotion, "3", "", times, path, ".mp3");
            } else if (type == 3) {// 多图
                Log.v(TAG, "多图");
                ArrayList<ContentListinfo> contentList_ = new ArrayList<ContentListinfo>();
                try {
                    for (int i = 0; i < EmmApplication.pir.size(); i++) {
                        ContentListinfo content = new ContentListinfo();
                        content.setFollowContent(EmmApplication.setPatchRtString(EmmApplication.pir.get(i).sourcePath));
                        contentList_.add(content);
                    }
                    addfollow(contentList_, customerId, SelectPotion, "2", ".jpg", "", "", "");
                } catch (Exception e) {
                    Loading.hideDialogForLoading();
                    handler.sendEmptyMessage(3);
                }
            }

            return null;
        }

        // 当在上面方法中调用publishProgress时，该方法触发,该方法在I线程中被执行
        protected void onProgressUpdate(Integer... progress) {
        }

        protected void onPostExecute(Void result) {
        }

        protected void onPreExecute() {
        }

    }

    /**
     * 8KHz录制MP3
     */
    private Mp3Recorder recorder_Mp3;

    /**
     * 音频名称
     */
    private String Mp3Name;

    /**
     * <p>
     * <b>Title：</b> 初始化MP3录音
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午3:05:02
     */
    private void InitMP3() {
        Mp3Name = System.currentTimeMillis() + ".mp3";
        patchMp3 = defPatch + "/" + Mp3Name;
        recorder_Mp3 = new Mp3Recorder();
    }

    GetCustomerDetail details;

    /**
     * <p>
     * <b>Title：</b> 客户详情
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param customerId
     * @author tangxin
     * @date 2016年12月7日 下午3:05:21
     */
    private void getCustomerDetail(String customerId) {
        EmmApplication.updateUrl("getCustomerDetail");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        map.put("projectCode", EmmApplication.getProjectCode());
        map.put("customerId", customerId);
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v(TAG, "getCustomerDetail-->post" + EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Loading.showDialogForLoading(FollowUpActivity.this, "正在加载...", false, true, 60000);
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }

                details = JSONObject.parseObject(resData.toString(), GetCustomerDetail.class);
                if ("1".equals(details.getResult())) {
                    user_name.setText(details.getCustomerName());
                    if (null != details.getCustomerStar() && !"".equals(details.getCustomerStar())) {
                        user_star.setVisibility("是".equals(details.getCustomerStar()) == true ? View.VISIBLE
                                : View.INVISIBLE);
                    } else {
                        user_star.setVisibility(View.INVISIBLE);
                    }
                    user_sex.setText(details.getCustomerSex());
                    user_number.setText(details.getIntentionLevel());
                    phone_tel.setText(details.getCustomerPhone());
                    customerStatus.setText(details.getCustomerStatus());
                    customerOrigin.setText(details.getCustomerOrigin());
                } else {
                    EmmApplication.T2(details.getErrorMsg());
                }
            }
        });
    }

    /**
     * 新增用户接口
     */
    AddCustomer addcustomer;

    /**
     * <p>
     * <b>Title：</b> 更新跟进记录
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午3:05:31
     */
    private void editFollow() {
        EmmApplication.updateUrl("editFollow");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        map.put("followId", FollowId);
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v(TAG, "getCustomerDetail-->post" + EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Loading.showDialogForLoading(FollowUpActivity.this, "正在加载...", false, true, 60000);
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                Log.v(TAG, "content:" + content);
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }

                addcustomer = JSONObject.parseObject(resData.toString(), AddCustomer.class);
                if ("1".equals(addcustomer.getResult())) {
                    EmmApplication.T2("跟进记录已生成");
                    finish();
                } else {
                    EmmApplication.T2(addcustomer.getErrorMsg());
                }
            }
        });
    }


}